package com.mgq.netty.bytebuff;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
@Slf4j
public class TestByteBuffer {

    public static void main(String[] args) {
        //1.获取FileChannel
        //1.输入输出流,2.RandomAccessFile
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()){
            ByteBuffer buffer = ByteBuffer.allocateDirect(10);
            while (true) {
                int len = channel.read(buffer);
                log.debug("读取到的长度是{}", len);
                if (len == -1) {
                    break;
                }
                //打印buff内容
                buffer.flip();//切换为读模式
                while (buffer.hasRemaining()) { //buff中还有剩余的内容
                    byte b = buffer.get();
                    log.debug("读取的内容是{}", (char)b);
                }
                //切换为写模式
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
